import os
from urllib.parse import quote

from django.http import HttpRequest, JsonResponse, HttpResponse, StreamingHttpResponse
from django.shortcuts import render, redirect
from django.db import IntegrityError

from vote.captcha import Captcha
from vote.models import Subject, Teacher, User, LoginLog
from vote.myforms import RegisterForm, LoginForm
from vote.utils import random_captcha_text


def show_subjects(request):
    """查看所有学科"""
    subjects = Subject.objects.all()
    return render(
        request,
        'subject.html',
        {
            'subjects': subjects
        }
    )


def show_teachers(request):
    """查看指定学科的老师"""
    try:
        sno = int(request.GET['sno'])
        subject = Subject.objects.filter(no=sno).first()
        teachers = Teacher.objects.filter(subject__no=sno)
        return render(
            request,
            'teacher.html',
            {
                'subject': subject,
                'teachers': teachers
            }
        )
    except KeyError:
        return redirect('/')
# HttpRequest - 封装了浏览器发给服务器的请求
# HttpResponse - 封装了服务器给浏览器的响应
# request.method - 获取请求的方法（GET / POST / PUT / DELETE）
# request.path - 获取请求的资源路径
# request.path_info - 获取带查询参数的资源路径（/praise/?tno=1&sno=1）
# request.META - 获取请求头
# request.GET / request.POST - 获取请求的参数
# request.body / request.FILES - 获取上传的文件


def praise_or_criticize(request: HttpRequest):
    """投票"""
    if 'user'in request.session:
        try:
            tno = int(request.GET['tno'])
            teacher = Teacher.objects.get(no=tno)
            if request.path.startswith('/vote/praise'):
                teacher.good_count += 1
            else:
                teacher.bad_count += 1
            teacher.save()
            data = {'code': 200, 'message': '操作成功'}
        except(KeyError, ValueError, Teacher.DoesNotExist):
            data = {'code': 404, 'message': '操作失败'}
    else:
        data = {'code': 401, 'message': '请登录'}
        # return HttpRequest(json.dumps(data), content_type='application/json; charset=utf8')
    return JsonResponse(data)


def get_captcha(request):
    """验证码"""
    captcha_text = random_captcha_text()
    request.session['captcha'] = captcha_text
    image_data = Captcha.instance().generate(captcha_text)
    return HttpResponse(image_data, content_type='image/png')


def logout(request):
    request.session.flush()
    return redirect('/')


def login(request):
    """登录"""
    hint = ''
    backurl = request.GET.get('backurl', '/')
    if request.method == 'POST':
        form = LoginForm(request.POST)
        backurl = request.POST.get('backurl', '/')
        if form.is_valid():
            captcha_from_user = form.cleaned_data['captcha']
            captcha_from_session = request.session.get('captcha')
            if captcha_from_user.lower() == captcha_from_session.lower():
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                user = User.objects.filter(username=username, password=password).first()
                if user:
                    request.session['user'] = user
                    login_log = LoginLog()
                    login_log.ip_addr = request.META.get('REMOTE_ADDR')
                    login_log.user = user
                    login_log.save()
                    return redirect(backurl)
                else:
                    hint = '用户名或密码错误'
            else:
                hint = '验证码错误'
        else:
            hint = '请输入有效的登录信息'
    return render(request, 'login.html', {'hint': hint, 'backurl': backurl})


def send_mobile_code(request, tel):
    print(type(tel))
    # redis_cli = get_redis_connection()
    # 强大的redis操控的模块

# def register(request):
#     """注册"""
#     hint = ''
#     if request.method == 'POST':
#         try:
#             form = RegisterForm(request.POST)
#             if form.is_valid():
#                 user = User()
#                 user.username = form.cleaned_data['username']
#                 user.password = form.cleaned_data['password']
#                 user.save()
#                 return render(request, 'login.html', {'hint': '注册成功,请登录'})
#             else:
#                 hint = '请输入有效的注册信息'
#         except IntegrityError:
#             hint = '用户名已被注册,请更换其他用户名'
#         except Exception:
#             hint = '网站正在升级,请稍后重试'
#     return render(request, 'register.html', {'hint': hint})
def register(request):
    """注册"""
    hint = ''
    if request.method == 'POST':
        try:
            form = RegisterForm(request.POST)
            if form.is_valid():
                print(form.errors)
                form.sava()
                return render(request, 'login.html', {'hint': '注册成功,请登录'})
            else:
                hint = '请输入有效的注册信息'
        except IntegrityError:
            hint = '用户名已被注册,请更换其他用户名'
        except Exception:
            hint = '网站正在升级,请稍后重试'
    return render(request, 'register.html', {'hint': hint})


def download_pdf(request):
    """下载pdf文件"""
    path = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(path, 'resources/python.pdf')
    buffer = b''
    with open(path,  'rb', ) as file_stream:
        buffer = file_stream.read()
    resp = HttpResponse(buffer, content_type='application/pdf')
    resp['content-disposition'] = 'attachment; filename="python.pdf"'
    return resp


def download_excel(request):
    """下载excel文件"""
    path = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(path, 'resources/qq123.xlsx')
    buffer = b''
    with open(path,  'rb', ) as file_stream:
        buffer = file_stream.read()
    resp = StreamingHttpResponse(buffer, content_type='application/vnd.ms-excel')
    filename = quote('空白.xlsx')
    resp['content-disposition'] = 'attachment; filename="%s"' % filename
    return resp
